package com.untrance.shop.core.service.bean;

import com.google.appengine.api.datastore.Key;
import com.untrance.shop.common.filters.model.CommentFilter;
import com.untrance.shop.common.utils.ClassUtils;
import com.untrance.shop.common.utils.PagerUtils;
import com.untrance.shop.common.vo.CommentVO;
import com.untrance.shop.core.dao.CommentDao;
import com.untrance.shop.core.dao.UserDao;
import com.untrance.shop.core.joiner.CommentJoiner;
import com.untrance.shop.core.service.CommentService;
import com.untrance.shop.model.Comment;
import com.untrance.shop.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author eugene zadyra
 */
@Service("commentService")
public class CommentServiceBean implements CommentService {

	@Autowired
	private CommentDao commentDao;
	@Autowired
	private UserDao userDao;

	@Override
	public List<CommentVO> getCommentsRelatedToProduct(Key productKey, Integer page, Integer itemsPerPage) {
		CommentFilter filter = PagerUtils.updateFilterPaginationInfo(new CommentFilter(), page, itemsPerPage);
		filter.setProductKey(productKey);
		List<Comment> comments = commentDao.findEntitiesByFilter(filter);
		if (comments != null && comments.size() > 0) {
			List<Key> userKeyList = ClassUtils.getUniqueFieldValueList(comments, "userKey");
			List<User> users = new ArrayList<User>(userDao.findEntitiesByKeyCollection(userKeyList));
			return new CommentJoiner(users).joinAll(comments);
		}
		return null;
	}

	@Override
	public Comment addComment(Comment comment) {
		return userDao.add(comment);
	}

	@Override
	public Integer getCommentsCountForProduct(Key productKey) {
		CommentFilter filter = new CommentFilter();
		filter.setProductKey(productKey);
		return commentDao.findEntitiesCountByFilter(filter);
	}
}
